import { Component, OnInit, ViewChild } from '@angular/core';
import _ from 'lodash';
import { toTree } from 'app/modules/share/components/tree/tree.component';
import { FormBuilder } from '@angular/forms';
import { BehaviorSubject } from 'rxjs';
import { first } from 'rxjs/operators';
import { DepartmentService, Department } from '../../services/department.service';
import { SweetAlertService } from 'app/modules/share/services/sweet-alert.service';

@Component({
	selector: 'm-department',
	templateUrl: './department.component.html',
	styleUrls: ['./department.component.scss'],
})
export class DepartmentComponent implements OnInit {
	constructor(
		private fb: FormBuilder,
		private departmentService: DepartmentService,
		private sweetAlert: SweetAlertService,
	) {}
	departments$ = new BehaviorSubject<Department[]>([]);
	ngOnInit() {
		this.getData();
	}

	async getData() {
		const list: Department[] = (await this.departmentService.list()).list;
		const tree = toTree(list, 'level_struct');
		this.departments$.next(tree);
		return tree;
	}

	createTemplate(parent_level = ''): Department {
		return {
			id: 0,
			name: '',
			des: '',
			level_struct: parent_level,
			children: [],
			editing: true,
		};
	}

	async add() {
		const tree = await this.departments$.pipe(first()).toPromise();
		tree.push(this.createTemplate());
	}

	addChild(department: Department) {
		department.children.push(this.createTemplate(department.level_struct));
	}

	async save(department: Department) {
		if (department.id) {
			await this.departmentService.update({
				id: department.id,
				name: department.name,
				des: department.des,
			});
		} else {
			await this.departmentService.create({
				name: department.name,
				des: department.des,
				parent_level_struct: department.level_struct,
			});
		}
		this.getData();
	}

	async delete(department: Department) {
		const result = await this.sweetAlert.confirm(`操作即时生效。确定要删除"${department.name}"吗？`);
		if (result.dismiss) {
			return;
		}
		await this.departmentService.delete([department.id]);
		this.getData();
	}
	cancel() {
		this.getData();
	}
}

const TestData = [
	{
		name: '部门',
		children: [{ name: '部分2', children: [] }],
	},
	{
		name: '部门3',
		children: [],
	},
];
